package filters

import (
  "github.com/valyala/fasthttp"
  "api/types"
  "github.com/dgrijalva/jwt-go"
  "bytes"
  "api/conf"
  "api/lib"
)
func NewFilterJwt() *FilterJwt{
  return &FilterJwt{}
}
type FilterJwt struct{}
func(fjwt *FilterJwt) Pre(proxyContext *types.ProxyContext,fasthttpCtx *fasthttp.RequestCtx)(bool,int,string){
  if checkIfIgnore(proxyContext){
    return true, 0, ""
  }
  skey,_ := conf.GetConfig().Get("app").GetString("jwt_key","")
  jwtToken := proxyContext.Header.Peek("Authorization")
  if jwtToken != nil && bytes.Index(jwtToken,[]byte("Bearer")) == 0{
    jwtToken = jwtToken[len("Bearer "):]
    tk, err := jwt.Parse(string(jwtToken), func(token *jwt.Token) (interface{}, error) {
      return []byte(skey), nil
    })
    if err != nil {
      return false, conf.REQUEST_INVALID_ACCESS_TOKEN, "jwt error : " + err.Error()
    }
    if claims, ok := tk.Claims.(jwt.MapClaims); ok &&  tk.Valid {
    	proxyContext.Identify = claims["user_name"].(string)
      //log.Success("%s",claims["user_name"])
      return true, 0, ""
    }
  }
  return false,conf.REQUEST_INVALID_ACCESS_TOKEN,"jwt error : jwt is not valid"
}
func (fjwt *FilterJwt) Post(proxyContext *types.ProxyContext,fasthttpCtx *fasthttp.RequestCtx)(bool,int,string){
  return true,0,""
}
func checkIfIgnore(proxyContext *types.ProxyContext) bool{
  cache := lib.NewCache()
  if _,err := cache.GetJwtIgnore(proxyContext.Mapkey);err == nil{
    return true
  }
  return false
}
